<?php



function checkSession(){


    
//kill session if idle for 30 min
$max_idle_time_minutes = MAX_IDLE_TIME_MINUTES;
$max_idle_time = $max_idle_time_minutes * 60; // conver to seconds

if (!isset($_SESSION['last_activity'])) $_SESSION['last_activity'] = time();

$time_diff =   intval(time() - $_SESSION['last_activity']);

 
/* echo      $_SESSION['last_activity']." - last activity <br>";
 echo      $max_idle_time." - max_idle_time <br>";
 echo      $time_diff." - time_diff <br>";
  */

 

if (isset($_SESSION['last_activity']) && ($time_diff > $max_idle_time)) {
     echo      ($time_diff > $max_idle_time)." - is expired <br>"; 
  //   exit;   
    // last request was more than 30 minates ago
    session_destroy();   // destroy session data in storage
    session_unset();     // unset $_SESSION variable for the runtime
    header("location:login_page.php");      
    
    
} else{
    // reset $_SESSION['last_activity'] = time();  // currrent time
    $_SESSION['last_activity'] = time();
}


    
    
}

function checkCurrentOS($_OS)
{
	if ( strcmp( $_OS, _CUR_OS ) == 0 ) {
		return true;
	}
	return false;
}

function fixUriPath($value){
	if (checkCurrentOS('Win')){
		$value =  str_replace("\\", "/", $value);
	}
	return $value;
}

function fixLocalPath($value){

	if (checkCurrentOS('Win')){
		$value =  str_replace("/", "\\", $value);
	}
	return $value;
}


function show_errors($wp_error, $narrow = false) {

	if ( $wp_error->get_error_code() ) {
		$errors = '';
		$messages = '';
		foreach ( $wp_error->get_error_codes() as $code ) {
			$severity = $wp_error->get_error_data($code);
			foreach ( $wp_error->get_error_messages($code) as $error ) {
				if ( 'message' == $severity )
					$messages .= '	' . $error . "<br />\n";
				else
					$errors .= '	' . $error . "<br />\n";
			}
		}

		$extra_class = ($narrow) ? 'narrow' : '';

		if ( !empty($errors) )
			echo '<div class="error '.$extra_class.'">' . apply_filters('login_errors', $errors) . "</div>\n";
		if ( !empty($messages) )
			echo '<div class="message '.$extra_class.'">' . apply_filters('login_messages', $messages) . "</div>\n";
	}
}


function create_thumbnails($imageFileName, $size ) {
 if ($size=='large'){
 $targetFolder = WBM_THUMBNAILS_LARGE_FOLDER; 
 $width  = WBM_THUMBNAIL_LARGE_WIDTH;
 $height= WBM_THUMBNAIL_LARGE_HEIGHT;
     
 }else{
 $targetFolder = WBM_THUMBNAILS_FOLDER; 
 $width  = WBM_THUMBNAIL_WIDTH;
 $height= WBM_THUMBNAIL_HEIGHT;
 
 }
  if (empty($imageFileName)) return false;
    
        $filename = $imageFileName;
        if(file_exists(WBM_FILE_UPLOAD_DIR.$filename)) {

            include_once(ABSPATH."inc/phpthumb/phpthumb.class.php");

            $phpThumb = new phpThumb();
            $phpThumb->setParameter('w', $width);
            $phpThumb->setParameter('h', $height);
            $phpThumb->setParameter('q', 80);
            $phpThumb->setSourceFilename(WBM_FILE_UPLOAD_DIR.$filename);
            $output_filename = $targetFolder.$filename;

            if ($phpThumb->GenerateThumbnail()) {
                $phpThumb->RenderToFile($output_filename);
               // echo "thumnail created to :".$output_filename;
            return true; 
            }
        }else{
        return false;
        }
    
}
function get_thumbnails_uri($imageFileName, $size) {
    
    if (empty($imageFileName)) return false;  
    if ($size=='large'){
     $targetFolder = WBM_THUMBNAILS_LARGE_FOLDER;     
    } else{
     $targetFolder = WBM_THUMBNAILS_FOLDER;     
    }
    $thumb_file_path = $targetFolder.$imageFileName;   
    if(!file_exists($thumb_file_path)) {
     // no thumbnail created yet, lets do it now..
     create_thumbnails($imageFileName, $size);
    }
    
    return $imageFileName;
        //return "tempItem.jpg";
}


function BBCode($Text)
        {
            // Replace any html brackets with HTML Entities to prevent executing HTML or script
            // Don't use strip_tags here because it breaks [url] search by replacing & with amp
            $Text = str_replace("<", "&lt;", $Text);
            $Text = str_replace(">", "&gt;", $Text);

           

            // Set up the parameters for a URL search string
            $URLSearchString = " a-zA-Z0-9\:\/\-\?\&\.\=\_\~\#\'";
            // Set up the parameters for a MAIL search string
            $MAILSearchString = $URLSearchString . " a-zA-Z0-9\.@";
            
            //Non BB URL Search
            //$Text = eregi_replace("([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])", "<a href=\"\\1://\\2\\3\" target=\"_blank\" target=\"_new\">\\1://\\2\\3</a>", $Text);
            //$Text = eregi_replace("(([a-z0-9_]|\\-|\\.)+@([^[:space:]]*)([[:alnum:]-]))", "<a href=\"mailto:\\1\" target=\"_new\">\\1</a>", $Text);
            if (substr($Text,0, 7) == "http://"){
            $Text = eregi_replace("([[:alnum:]]+)://([^[:space:]]*)([[:alnum:]#?/&=])", "<a href=\"\\1://\\2\\3\">\\1://\\2\\3</a>", $Text);
             // Convert new line chars to html <br /> tags
            $Text = nl2br($Text);
            } else { 
            // Perform URL Search
            $Text = preg_replace("/\[url\]([$URLSearchString]*)\[\/url\]/", '<a href="javascript:go(\'$1\',\'new\')">$1</a>', $Text);
            $Text = preg_replace("(\[url\=([$URLSearchString]*)\](.+?)\[/url\])", '<a href="javascript:go(\'$1\',\'new\')">$2</a>', $Text);
            //$Text = preg_replace("(\[url\=([$URLSearchString]*)\]([$URLSearchString]*)\[/url\])", '<a href="$1" target="_blank">$2</a>', $Text);
             // Convert new line chars to html <br /> tags
            $Text = nl2br($Text);
            }
            // Perform MAIL Search
            $Text = preg_replace("(\[mail\]([$MAILSearchString]*)\[/mail\])", '<a href="mailto:$1">$1</a>', $Text);
            $Text = preg_replace("/\[mail\=([$MAILSearchString]*)\](.+?)\[\/mail\]/", '<a href="mailto:$1">$2</a>', $Text);
            
            // Check for bold text
            $Text = preg_replace("(\[b\](.+?)\[\/b])is",'<span class="bold">$1</span>',$Text);

            // Check for Italics text
            $Text = preg_replace("(\[i\](.+?)\[\/i\])is",'<span class="italics">$1</span>',$Text);

            // Check for Underline text
            $Text = preg_replace("(\[u\](.+?)\[\/u\])is",'<span class="underline">$1</span>',$Text);

            // Check for strike-through text
            $Text = preg_replace("(\[s\](.+?)\[\/s\])is",'<span class="strikethrough">$1</span>',$Text);

            // Check for over-line text
            $Text = preg_replace("(\[o\](.+?)\[\/o\])is",'<span class="overline">$1</span>',$Text);

            // Check for colored text
            $Text = preg_replace("(\[color=(.+?)\](.+?)\[\/color\])is","<span style=\"color: $1\">$2</span>",$Text);

            // Check for sized text
            $Text = preg_replace("(\[size=(.+?)\](.+?)\[\/size\])is","<span style=\"font-size: $1px\">$2</span>",$Text);

            // Check for list text
            $Text = preg_replace("/\[list\](.+?)\[\/list\]/is", '<ul class="listbullet">$1</ul>' ,$Text);
            $Text = preg_replace("/\[list=1\](.+?)\[\/list\]/is", '<ul class="listdecimal">$1</ul>' ,$Text);
            $Text = preg_replace("/\[list=i\](.+?)\[\/list\]/s", '<ul class="listlowerroman">$1</ul>' ,$Text);
            $Text = preg_replace("/\[list=I\](.+?)\[\/list\]/s", '<ul class="listupperroman">$1</ul>' ,$Text);
            $Text = preg_replace("/\[list=a\](.+?)\[\/list\]/s", '<ul class="listloweralpha">$1</ul>' ,$Text);
            $Text = preg_replace("/\[list=A\](.+?)\[\/list\]/s", '<ul class="listupperalpha">$1</ul>' ,$Text);
            $Text = str_replace("[*]", "<li>", $Text);

            // Check for font change text
            $Text = preg_replace("(\[font=(.+?)\](.+?)\[\/font\])","<span style=\"font-family: $1;\">$2</span>",$Text);

            // Declare the format for [code] layout
            $CodeLayout = '<table width="90%" border="0" align="center" cellpadding="0" cellspacing="0">
                                <tr>
                                    <td class="quotecodeheader"> Code:</td>
                                </tr>
                                <tr>
                                    <td class="codebody">$1</td>
                                </tr>
                           </table>';
            // Check for [code] text
            $Text = preg_replace("/\[code\](.+?)\[\/code\]/is","$CodeLayout", $Text);

            // Declare the format for [quote] layout
            $QuoteLayout = '<table width="90%" border="0" align="center" cellpadding="0" cellspacing="0">
                                <tr>
                                    <td class="quotecodeheader"> Quote:</td>
                                </tr>
                                <tr>
                                    <td class="quotebody">$1</td>
                                </tr>
                           </table>';
                           
            // Check for [code] text
            $Text = preg_replace("/\[quote\](.+?)\[\/quote\]/is","$QuoteLayout", $Text);
            
            // Images
            // [img]pathtoimage[/img]
            $Text = preg_replace("/\[img\](.+?)\[\/img\]/", '<img src="$1">', $Text);
            
            // [img=widthxheight]image source[/img]
            $Text = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.+?)\[\/img\]/", '<img src="$3" height="$2" width="$1">', $Text);
            
            return $Text;
        }


//END 3rd PARTY CODE


//quick script to make the data look nice
function formatDate($val)  
  {  
      list($date, $time) = explode(" ", $val);  
      list($year, $month, $day) = explode("-", $date);
      list($hour, $minute, $second) = explode (":", $time);
      //return date("l, m.j.y @ H:ia", mktime($hour, $minute, $second, $month, $day, $year));  
      return date("j/m/y", mktime($hour, $minute, $second, $month, $day, $year));  
  } 

  //quick script to make the data look nice
function getPagingLinks($page=1,$wbm_id=0,$fb_user )  
  {  

$rowsPerPage = ITEMS_PER_PAGE;    

if (!$page){$page=1;}
// by default we show first page
$pageNum = $page;

// if $_GET['page'] defined, use it as page number

// counting the offset
$offset = ($pageNum - 1) * $rowsPerPage;

// ... the previous code

// how many rows we have in database

$query   = "SELECT COUNT(id) AS numrows FROM wbm_blonde_moments where wbm_active=1";
$result  = mysql_query($query) or die('Error, query failed');
$row     = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];

// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);
if ($maxPage<1) $maxPage=1;
// print the link to access each page
$self = $_SERVER['PHP_SELF'];
$nav  = '';


if ($pageNum > 1)
{
   $page  = $pageNum - 1;
   $prev  = "<a href=\"$self?wbm_id=$wbm_id&fb_user=$fb_user&page=$page\"><img src=\"images/previous.gif\" alt=\"Previous\" class=\"btnPrevious2\" /></a>";

  // $first = " <a href=\"$self?wbm_id=$wbm_id&fb_user=$fb_user&page=1\">[First Page]</a> ";
}
else
{
   $prev  = '&nbsp;'; // we're on page one, don't print previous link
   $first = '&nbsp;'; // nor the first page link
}

if ($pageNum < $maxPage)
{
   $page = $pageNum + 1;
  // $next = "<li> <a href=\"$self?wbm_id=$wbm_id&fb_user=$fb_user&page=$page\">Next ".$rowsPerPage."<img src=\"images/next.gif\" alt=\"Next\" class=\"btnNext2\" /></a> </li>";
   $next = "<a href=\"$self?wbm_id=$wbm_id&fb_user=$fb_user&page=$page\"><img src=\"images/next.gif\" alt=\"Next\" class=\"btnNext2\" /></a>";

 //  $last = " <a href=\"$self?wbm_id=$wbm_id&fb_user=$fb_user&page=$maxPage\">[Last Page]</a> ";
}
else
{
   $next = '&nbsp;'; // we're on the last page, don't print next link
   $last = '&nbsp;'; // nor the last page link
}

echo  $prev . " Page $pageNum of $maxPage " . $next ;

} 

  
function getCommentPagingLinks($cPage=1,$wbm_id=0,$fb_user ){  
if ($wbm_id==0)      return "Error, wbm_id is required";
// how many rows to show per page

$rowsPerPage = COMMENT_ITEMS_PER_PAGE;    

if (!$cPage){$cPage=1;}
// by default we show first page
$pageNum = $cPage;

// if $_GET['page'] defined, use it as page number

// counting the offset
$offset = ($pageNum - 1) * $rowsPerPage;

// ... the previous code

// how many rows we have in database

$query   = "SELECT COUNT(commentid) AS numrows FROM wbm_comments where wbm_id=".$wbm_id;     
$result  = mysql_query($query) or die('Error, query failed');
$row     = mysql_fetch_array($result, MYSQL_ASSOC);
$numrows = $row['numrows'];

// how many pages we have when using paging?
$maxPage = ceil($numrows/$rowsPerPage);
if ($maxPage<1) $maxPage=1;
// print the link to access each page
$self = $_SERVER['PHP_SELF'];
$nav  = '';


if ($pageNum > 1)
{
   $cPage  = $pageNum - 1;
   $prev  = "<a href=\"$self?wbm_id=$wbm_id&fb_user=$fb_user&cPage=$cPage\"><img src=\"images/previous.gif\" alt=\"Previous\" class=\"btnPrevious2\" /></a>";

  // $first = " <a href=\"$self?wbm_id=$wbm_id&fb_user=$fb_user&page=1\">[First Page]</a> ";
}
else
{
   $prev  = '&nbsp;'; // we're on page one, don't print previous link
   $first = '&nbsp;'; // nor the first page link
}

if ($pageNum < $maxPage)
{
   $cPage = $pageNum + 1;
  // $next = "<li> <a href=\"$self?wbm_id=$wbm_id&fb_user=$fb_user&page=$page\">Next ".$rowsPerPage."<img src=\"images/next.gif\" alt=\"Next\" class=\"btnNext2\" /></a> </li>";
   $next = "<a href=\"$self?wbm_id=$wbm_id&fb_user=$fb_user&cPage=$cPage\"><img src=\"images/next.gif\" alt=\"Next\" class=\"btnNext2\" /></a>";

 //  $last = " <a href=\"$self?wbm_id=$wbm_id&fb_user=$fb_user&page=$maxPage\">[Last Page]</a> ";
}
else
{
   $next = '&nbsp;'; // we're on the last page, don't print next link
   $last = '&nbsp;'; // nor the last page link
}



echo  '<li>'.$prev .'</li>'. " Page $pageNum of $maxPage " .'<li>'. $next.'</li>' ;    

} 

  
function getFBusername($fb_user_id) {
$fb_username="@#~*!!Error";

if (intval($fb_user_id)<1) return $fb_username;
if (!isset($new_facebook)) $new_facebook = new Facebook($fb_api_key, $fb_api_secret);

$user_details = $new_facebook->api_client->users_getInfo($fb_user_id, array('name'));
//print_r($user_details);
$fullName = $user_details[0]['name'];
if (!empty($fullName)){
 $fb_username =  $fullName;  
} 
return $fb_username;
} 
//echo "functions";



//truncate for number of characters
function truncate_string($string, $max_length = WBM_TRUNCATE_LENGTH) {
    if (strlen($string) > $max_length) {
         $string = substr($string, 0, $max_length);
         $string .= '...';
    }
  return $string;
}

// facebook functions

function get_facebook(){
    global $facebook, $fb_api_key, $fb_api_secret;
    
    if (!isset($facebook) || !is_object($facebook)){
        
require_once (ABSPATH.'inc/facebook/facebook.php'); 
$facebook = new Facebook($fb_api_key, $fb_api_secret);      
 
    }
    return $facebook;
}

function getFBUserImage($userid,$current=false){
    global $facebook, $fb_user_details;
    $picUrl = "";
    
    
    //print_r($fb_user_details);
    if ($current){
        if (isset($fb_user_details['pic_small'])) {
            $picUrl=$fb_user_details['pic_small'] ;
        }else{
            $picUrl=WBM_FB_DEFAULT_IMAGE;
        }
        return $picUrl;
    }else{
        
         if (!isset($facebook) || !is_object($facebook)){ $facebook = get_facebook();} 
  //  echo $userid;
        $user_details = $facebook->api_client->users_getInfo($userid, 'pic_small'); 

        
      
            
        if (sizeof($user_details)>0 && is_array($user_details)) {
            if (!empty($user_details[0]['pic_small'])) $picUrl  = $user_details[0]['pic_small'];    
        }
    
 
 if (!inStr('http://',$picUrl )) $picUrl = WBM_FB_DEFAULT_IMAGE;
    }
    

   
 
 return $picUrl;
    
 
}


function inStr ($needle, $haystack)
{
  $needlechars = strlen($needle); //gets the number of characters in our needle
  $i = 0;
  for($i=0; $i < strlen($haystack); $i++) //creates a loop for the number of characters in our haystack
  {
    if(substr($haystack, $i, $needlechars) == $needle) //checks to see if the needle is in this segment of the haystack
    {
      return TRUE; //if it is return true
    }
  }
  return FALSE; //if not, return false
} 

function clean_for_mysql($string) {  
$new_string="";      
  $in_string = ltrim($string);       
  $in_string = rtrim($in_string);
    
  $max_length = 131072; // 128K
  
  if (strlen($in_string) > $max_length) {
    $new_string = substr($in_string,0,$max_length);
  }
  $new_string = mysql_real_escape_string($new_string);
  return $new_string;
}


